package com.df.ez_game.server.logic;

import com.df.ez_game.EZGameCtx;
import com.df.ez_game.server.NodeType;
import com.df.ez_game.server.ServerNode;
import com.df.ez_game.server.UserSession;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.Attribute;
import lombok.extern.slf4j.Slf4j;

import java.util.UUID;

@Slf4j
public class SessionHandler extends ChannelInboundHandlerAdapter {
    ServerNode serverNode;

    public SessionHandler(ServerNode serverNode){
        this.serverNode = serverNode;
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        if(serverNode.getType()== NodeType.SingletonLogic){
            LogicServerNode sn = (LogicServerNode) serverNode;
            UserSession session = new UserSession();
            session.setSessionId(UUID.randomUUID().toString());
            session.setChannel(ctx.channel());
            session.setState("connected");
            sn.getSessions().put(ctx.channel().id(), session);

            ISessionLifecycle sessionLifecycle = sn.getSettings().getSessionLifecycle();
            if(sessionLifecycle!=null){
                sessionLifecycle.onActive(ctx,session);
            }
        }
        super.channelActive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        if(serverNode.getType()== NodeType.SingletonLogic){
            LogicServerNode sn = (LogicServerNode) serverNode;

            UserSession session = sn.getSessions().get(ctx.channel().id());
            ISessionLifecycle sessionLifecycle = sn.getSettings().getSessionLifecycle();
            if(sessionLifecycle!=null){
                sessionLifecycle.onException(ctx,cause,session);
            }
        }
        super.exceptionCaught(ctx, cause);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        if(serverNode.getType()== NodeType.SingletonLogic){
            LogicServerNode sn = (LogicServerNode) serverNode;

            UserSession session = sn.getSessions().remove(ctx.channel().id());
            ISessionLifecycle sessionLifecycle = sn.getSettings().getSessionLifecycle();
            Attribute<Long> attr = ctx.channel().attr(EZGameCtx.loginId);
            if(attr.get()!=null){
                sn.getLoginSessions().remove(attr.get());
                if(sessionLifecycle!=null){
                    sessionLifecycle.onLoginOut(ctx.channel(),session);
                }
            }

            if(sessionLifecycle!=null){
                sessionLifecycle.onInactive(ctx,session);
            }
        }
        super.handlerRemoved(ctx);
    }
}
